package com.ellricky.baselib.ui.xufei;

import android.os.Build;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.andr.common.http.callback.JOCallback;
import com.andr.common.util.EmptyUtil;
import com.andr.common.util.ToastUtil;
import com.ellricky.baselib.BaseConstant;
import com.ellricky.baselib.R;
import com.ellricky.baselib.adapter.CommonGridItemDecoration;
import com.ellricky.baselib.adapter.xufei.PayUploadAdapter;
import com.ellricky.baselib.cache.LocalCacheUtil;
import com.ellricky.baselib.dialog.picker.EPickerEntityListener;
import com.ellricky.baselib.dialog.picker.EPickerUtil;
import com.ellricky.baselib.entity.IdNamePickerEntity;
import com.ellricky.baselib.entity.xufei.PayUploadEntity;
import com.ellricky.baselib.http.HttpUtils;
import com.ellricky.baselib.ui.base.BaseTakePhotoActivity;
import com.ellricky.baselib.ui.order.OrderDetail;
import com.ellricky.baselib.util.EAppUtil;
import com.ellricky.baselib.util.EDialogUtil;
import com.ellricky.baselib.util.FileUtil;
import com.ellricky.baselib.util.NewEntityCallback;
import com.ellricky.baselib.widget.EditItemView;
import com.flyco.roundview.RoundTextView;

import org.devio.takephoto.model.TResult;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.ellricky.baselib.BaseConstant.RESULT_CODE_ADD;

/**
 * 续费
 */
public class PriceAddActivity extends BaseTakePhotoActivity implements AdapterView.OnItemClickListener {
    private EditItemView etVip;
    private EditItemView etMoney;
    private RecyclerView rvUpload;
    private RoundTextView btnSubmit;

    private String memberId;
    private String from; //student来自学生缴费，clue来自线索缴费
    private EPickerUtil ePickerUtil;
    private IdNamePickerEntity selVipCard;

    private PayUploadAdapter adapter;
    private List<PayUploadEntity> list;
    private int curItemPos = -1;
    private OrderDetail orderDetail;

    @Override
    public int getContentLayout() {
        return R.layout.base_activity_price_add;
    }

    @Override
    public void initUIView() {
        super.initUIView();
        memberId = getIntent().getStringExtra(BaseConstant.KEY_ID);
        from = getIntent().getStringExtra(BaseConstant.KEY_FROM);
        orderDetail = getIntent().getParcelableExtra(BaseConstant.KEY_ORDER);

        ePickerUtil = new EPickerUtil(this);
        mTvTitle.setText(R.string.base_stu_price_add);

        etVip = findViewById(R.id.etVip);
        etMoney = findViewById(R.id.etMoney);
        rvUpload = findViewById(R.id.rvUpload);

        btnSubmit = findViewById(R.id.btnSubmit);

        etMoney.setInputDecimal();

        etVip.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        //如果从订单详情跳转 则从订单里面取member_id
        if (orderDetail != null) {
            memberId = orderDetail.getLog_member_id() + "";
            selVipCard = new IdNamePickerEntity(orderDetail.getLog_product_id() + "", orderDetail.getLog_product_Name());
            etVip.setValue(orderDetail.getLog_product_Name());
        }
        initRv();

    }

    private void initRv() {
        GridLayoutManager glm1 = new GridLayoutManager(this, 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        rvUpload.setLayoutManager(glm1);
        rvUpload.addItemDecoration(new CommonGridItemDecoration(this, 3, 20, false));
        rvUpload.setNestedScrollingEnabled(false);

        adapter = new PayUploadAdapter(this);
        adapter.setOnItemClickListener(this);
        rvUpload.setAdapter(adapter);

        list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            list.add(new PayUploadEntity());

        }
        if (orderDetail != null) {
            String img = orderDetail.getLog_img();
            String img2 = orderDetail.getLog_img2();
            String img3 = orderDetail.getLog_img3();
            if (img != null && !img.isEmpty()) {
                list.get(0).setImageUrl(img);
            }

            if (img2 != null && !img2.isEmpty()) {
                list.get(1).setImageUrl(img2);
            }

            if (img3 != null && !img3.isEmpty()) {
                list.get(2).setImageUrl(img3);
            }
        }
        adapter.refresh(list);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PayUploadEntity entity = adapter.get(position);
        String url = entity.getImageUrl();
        // 上传图片
        curItemPos = position;
        EDialogUtil.showTakePhotoDialog(this, this);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void takeSuccess(TResult result) {
        String picUrl = result.getImage().getCompressPath();
        uploadPhoto(picUrl);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void uploadPhoto(String picPath) {
        // 接口提交
        if (EmptyUtil.isEmpty(picPath)) {
            ToastUtil.show(this, "图片路径为空");
            return;
        }

        if (!EmptyUtil.isEmpty(picPath)) {
            list.get(curItemPos).setImageUrl(picPath);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onClickView(View v) {
        super.onClickView(v);
        if (v == etVip) {
            ePickerUtil.checkStuVipPicker(selVipCard, new EPickerEntityListener<IdNamePickerEntity>() {
                @Override
                public void onSelectItem(int pickType, IdNamePickerEntity idNamePickerEntity) {
                    selVipCard = idNamePickerEntity;
                    etVip.setValue(idNamePickerEntity.getName());
                }
            });
            return;
        }
        if (v == btnSubmit) {
            postSubmit();
        }
    }

    private void postSubmit() {
        String vipCard = etVip.getValue();
        if (EmptyUtil.isEmpty(vipCard)) {
            ToastUtil.show(this, R.string.base_vip_type_select);
            return;
        }

        String money = etMoney.getValue();
        if (EmptyUtil.isEmpty(money)) {
            ToastUtil.show(this, R.string.base_money_goon_input);
            return;
        }

        String url1 = "";
        String url2 = "";
        String url3 = "";
        for (PayUploadEntity entity : list) {
            String url = entity.getImageUrl();
            if (!EmptyUtil.isEmpty(url)) {
                if (url1.isEmpty()) {
                    url1 = FileUtil.fileToBase64(url);
                    continue;
                }
                if (url2.isEmpty()) {
                    url2 = FileUtil.fileToBase64(url);
                    continue;
                }
                if (url3.isEmpty()) {
                    url3 = FileUtil.fileToBase64(url);
                    continue;
                }
            }
        }

        String url = EAppUtil.getApiHost();
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("action", getAction());
        paramMap.put("member_id", memberId);
        paramMap.put("member_product_id", selVipCard.getId());
        paramMap.put("amount", money);
        paramMap.put("img", url1);
        paramMap.put("img2", url2);
        paramMap.put("img3", url3);
        paramMap.put("basic_num_give", "0");
        paramMap.put("special_num_give", "0");
        paramMap.put("art_num_give", "0");
        paramMap.put("eid", LocalCacheUtil.getUid());
        if (orderDetail != null) {
            paramMap.put("log_id", orderDetail.getLog_id() + "");
        }
        HttpUtils.getInstance().postFrom(url, paramMap, new NewEntityCallback<Object>(this) {

            @Override
            public void onSuccess(Object var1, String var2) {
                if (orderDetail != null) {
                    ToastUtil.show(PriceAddActivity.this, "修改成功");
                } else {
                    ToastUtil.show(PriceAddActivity.this, "缴费成功");
                }
                setResult(RESULT_CODE_ADD);
                finish();
            }
        });
    }

    private String getAction() {
        if (LocalCacheUtil.isPresidentRole()) {
            return "gzaPay";
        } else if (LocalCacheUtil.isTmRole()) {
            return "gzaPay";
        } else if (LocalCacheUtil.isTcRole()) {
            return "teacherPay";
        } else if (LocalCacheUtil.isConsultantRole()) {
            return "salePay";
        }
        return "";
    }
}
